import { Application } from 'egg'
import { Schema, ObjectId, Types } from 'mongoose'
import * as AutoIncrementFactory from 'mongoose-sequence'

export interface WorkProps {
  uuid: string
  title: string
  desc?: string
  coverImg?: string
  content?: Record<string, any>
  isTemplate?: boolean
  isPublic?: boolean
  isHot?: boolean
  author?: string
  copiedCount: number
  status: 0 | 1 | 2
  user: ObjectId
  autoIncrementId: number
}

export default (app: Application) => {
  const AutoIncrement = AutoIncrementFactory(app.mongoose)
  const WorkSchema = new Schema<WorkProps>(
    {
      uuid: { type: String, unique: true, required: true },
      title: { type: String, required: true },
      desc: { type: String },
      coverImg: { type: String },
      content: { type: String },
      isTemplate: { type: Boolean },
      isPublic: { type: Boolean },
      isHot: { type: Boolean },
      author: { type: String },
      copiedCount: { type: Number, default: 0 },
      status: { type: Number, default: 0 },
      user: { type: Types.ObjectId, ref: 'User', required: true },
    },
    {
      timestamps: true,
      toJSON: {
        transform: (_doc, ret) => {
          delete ret.__v
          delete ret._id
        },
      },
    },
  )
  WorkSchema.plugin(AutoIncrement, { inc_field: 'autoIncrementId', id: 'work_schema_seq' })
  return app.mongoose.model<WorkProps>('Work', WorkSchema)
}
